package com.alias.DAO.interfaces.impl;


import com.alias.DAO.interfaces.EmployeesDAO;
import com.alias.HibernateUtil;
import com.alias.model.Employees;
import org.hibernate.Session;


import javax.swing.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class EmployeesDAOImpl implements EmployeesDAO {
    @Override
    public void addEmployee(Employees employee) throws SQLException {
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            session.save(employee);
            session.getTransaction().commit();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка при вставке", JOptionPane.OK_OPTION);
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }

    }

    @Override
    public List<Employees> getEmployeesList() {
        Session session = null;
        List employees = new ArrayList<Employees>();
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            employees = session.createCriteria(Employees.class).list();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка 'getAll'", JOptionPane.OK_OPTION);
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return employees;
    }

    @Override
    public void updateEmployees(List <Employees> employeesList) {
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            for (Employees employee : employeesList){
                session.update(employee);
            }
            session.getTransaction().commit();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка 'getAll'", JOptionPane.OK_OPTION);
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }

    }
}
